# define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"

void StackInit(ST* ps)
{
	STDataType* tmp = (STDataType*)malloc(4 * sizeof(STDataType));
	if (NULL == tmp)
	{
		printf("fail\n");
		exit(-1);
	}
	ps->a = tmp;
	ps->capacity = 4;
	ps->top = 0;
}


void StackPush(ST* ps, STDataType x)
{
	assert(ps);
	if (ps->top == ps->capacity)
	{
		STDataType* tmp = (STDataType*)realloc(ps->a, 2 * ps->capacity * sizeof(STDataType));
		if (NULL == tmp)
		{
			printf("realloc fail!\n");
			exit(-1);
		}
		else
		{
			ps->a = tmp;  
		}
	}
	ps->a[ps->top] = x;
	ps->capacity *= 2;
	ps->top++;
}


void StackPop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);
	ps->top--;
}


int StackEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}


STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);
	return ps->a[ps->top - 1];
}


int StackSize(ST* ps)
{
	assert(ps);
	return ps->top;
}


void StackDestory(ST* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}